# LuckPay Web Manage System
#
# Copyright (c) 2016 Lucky Byte, Inc.
#
express = require 'express'
pgsql   = require 'pg'
fs      = require 'fs'
router = express.Router()
module.exports = router

router.all '/', (req, res, next) ->
    await pgsql.connect settings.pgsql_url, defer err, client, done
    if err then done(client); return next(err)

    where_clause = "(
        name like $1 or script like $1 or notes like $1
    )"
    res.locals.engine = req.body.engine or ''
    if res.locals.engine.length > 0
        where_clause += " and engine = #{res.locals.engine}"

    res.locals.status = req.body.status or ''
    if res.locals.status.length > 0
        where_clause += " and status = #{res.locals.status}"

    # 查询记录总数
    await client.query "select count(*) as count from pay_sched
        where #{ where_clause }", [
            '%' + res.locals.keyword + '%'
        ], defer err, result
    if err then done(client); return next(err)
    res.locals.total = result.rows[0].count

    # 查询当前页面中显示的记录
    await client.query "select * from pay_sched where #{ where_clause }
        order by serial offset $2::int limit $3::int", [
            '%' + res.locals.keyword + '%',
            res.locals.offset,
            res.locals.page_rows
        ], defer err, result
    if err then done(client); return next(err)
    done()
    res.render 'sched/index', records: result.rows


router.get '/new', (req, res, next) ->
    res.locals.breadcrumbs.push 'title': '新增定时任务'
    res.render 'sched/new', record: {}


router.post '/new', (req, res, next) ->
    for k in ['name', 'cron', 'engine']
        return next(new Error("请求缺少参数[#{k}]")) if not req.body[k]

    await pgsql.connect settings.pgsql_url, defer err, client, done
    if err then done(client); return next(err)

    await client.query \
        "insert into pay_sched (
            ctime, name, cron, status, engine, script, params, notes
        ) values (
            CURRENT_TIMESTAMP, $1, $2, $3, $4, $5, $6, $7
        ) returning serial", [
            req.body.name,
            req.body.cron,
            if req.body.status is 'on' then 1 else 0,
            req.body.engine,
            req.body.script,
            req.body.params,
            req.body.notes
        ], defer err, result
    if err then done(client); return next(err)

    new_serial = result.rows[0].serial
    await client.query """
            notify pay_sched, '{action:"add", serial:#{new_serial}}'
        """, defer err, client
    done()
    res.redirect '/sched'


router.get '/edit/:id', (req, res, next) ->
    res.locals.breadcrumbs.push 'title': '编辑定时任务'

    await pgsql.connect settings.pgsql_url, defer err, client, done
    if err then done(client); return next(err)

    await client.query "select * from pay_sched where serial = $1", [
            req.params.id
        ], defer err, result
    if err then done(client); return next(err)
    done()
    res.render 'sched/edit', record: result.rows[0]


router.post '/edit', (req, res, next) ->
    for k in ['serial', 'name', 'cron', 'engine']
        return next(new Error("请求缺少参数[#{k}]")) if not req.body[k]

    await pgsql.connect settings.pgsql_url, defer err, client, done
    if err then done(client); return next(err)

    await client.query \
        "update pay_sched set
            name = $1, cron = $2, status = $3, engine = $4,
            script = $5, params = $6, notes = $7
        where serial = $8", [
            req.body.name,
            req.body.cron,
            if req.body.status is 'on' then 1 else 0,
            req.body.engine,
            req.body.script,
            req.body.params,
            req.body.notes
            req.body.serial
        ], defer err, result
    if err then done(client); return next(err)

    await client.query """
            notify pay_sched, '{action:"modify", serial:#{req.body.serial}}'
        """, defer err, client
    done()
    res.redirect '/sched'


router.post '/delete', (req, res, next) ->
    res.type 'json'
    for k in ['serial']
        return next(new Error("请求缺少参数[#{k}]")) if not req.body[k]

    await pgsql.connect settings.pgsql_url, defer err, client, done
    if err then done(client); return next(err)

    await client.query \
        "delete from pay_sched where serial = $1", [
            req.body.serial
        ], defer err, result
    if err then done(client); return next(err)

    await client.query """
            notify pay_sched, '{action:"delete", serial:#{req.body.serial}}'
        """, defer err, client
    done()
    res.json succ: true, redirect: '/sched'


router.post '/trigger', (req, res, next) ->
    res.type 'json'
    for k in ['serial']
        return next(new Error("请求缺少参数[#{k}]")) if not req.body[k]

    await pgsql.connect settings.pgsql_url, defer err, client, done
    if err then done(client); return next(err)

    await client.query """
            notify pay_sched, '{action:"trigger", serial:#{req.body.serial}}'
        """, defer err, client
    done()
    res.json succ: true


router.all '/doc/:topic', (req, res, next) ->
    res.locals.breadcrumbs.push 'title': '说明文档'
    res.render "sched/doc/#{req.params.topic}"
